/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
  // 前序遍历回溯
    void binaryTreePaths(TreeNode* node, vector<int>& path, vector<string>& res){
        path.push_back(node->val);
        if(node->left == nullptr && node->right == nullptr){
            // 遇到叶子节点，将path转为string保存res中
            string temp;
            for(size_t i = 0; i < path.size()-1; ++i){
                temp += to_string(path[i]);
                temp += "->";
            }
            // 处理最后一个节点
            temp += to_string(path[path.size()-1]);
            res.push_back(temp);
        }
        if(node->left != nullptr){
            binaryTreePaths(node->left, path, res);
            // 回溯
            path.pop_back();
        }
        if(node->right != nullptr){
            binaryTreePaths(node->right, path, res);
            // 回溯
            path.pop_back();
        }
        return;
    }

    vector<string> binaryTreePaths(TreeNode* root) {
        vector<int> path;
        vector<string> res;
        binaryTreePaths(root, path, res);
        return res;
    }
};